package utils

import (
	"github.com/alomerry/copier"
	"reflect"
	"time"
)

const (
	RFC3339Milli = "2006-01-02T15:04:05.999Z07:00"
)

func RFC3339Convertor(m copier.Mapper) {
	registerRFC3339TimeToStringConverter(m)
	registerStringToRFC3339TimeConverter(m)
}

func registerRFC3339TimeToStringConverter(m copier.Mapper) {
	m.RegisterConverter(
		copier.Target{
			From: reflect.TypeOf(time.Time{}),
			To:   reflect.TypeOf(""),
		},
		func(from reflect.Value, _ reflect.Type) (reflect.Value, error) {
			if timeValue, ok := from.Interface().(time.Time); ok {
				if timeValue.Unix() > 0 {
					return reflect.ValueOf(timeValue.Format(RFC3339Milli)), nil
				} else {
					return reflect.ValueOf(""), nil
				}
			}
			return from, nil
		},
	)
}

func registerStringToRFC3339TimeConverter(m copier.Mapper) {
	m.RegisterConverter(
		copier.Target{
			From: reflect.TypeOf(""),
			To:   reflect.TypeOf(time.Time{}),
		},
		func(from reflect.Value, _ reflect.Type) (reflect.Value, error) {
			if str, ok := from.Interface().(string); ok {
				t, err := time.Parse(RFC3339Milli, str)
				if err != nil {
					return reflect.ValueOf(time.Time{}), nil
				}
				return reflect.ValueOf(t), nil
			}
			return from, nil
		},
	)
}
